package com.wl.mvi.main.tab

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wl.lib.widget.RecyclerAdapter
import com.wl.mvi.databinding.BlogTabListBinding


/**
 *
 * Created by wangliang on 2024/12/3
 */
class TabOneView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val binding = BlogTabListBinding.inflate(LayoutInflater.from(context), this)

    private val adapter: RecyclerAdapter by lazy {
        RecyclerAdapter().apply {
            registerViewType<TabOneItemView, TabOneItem> { itemView, item, _ ->
                itemView.render()
            }
        }
    }

    init {
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.recyclerView.adapter = adapter
    }

    private val itemTouchCallback = object :
        ItemTouchHelper.SimpleCallback(0, 0) {

        override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
            val dragDirs = ItemTouchHelper.UP or ItemTouchHelper.DOWN
            val swapFlags = 0
            return makeMovementFlags(dragDirs, swapFlags)
        }

        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            val from = viewHolder.bindingAdapterPosition
            val to = target.bindingAdapterPosition
            if (to < 0 || to > adapter.data.lastIndex) {
                return false
            }
            Log.d("WLTest", "move from $from to $to")
            adapter.notifyItemMoved(from, to)
            return true
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

        }
    }

    fun render(data: TabOne) {
        ItemTouchHelper(itemTouchCallback).attachToRecyclerView(binding.recyclerView)
        adapter.data.clear()
        adapter.data.addAll(data.list)
        adapter.notifyDataSetChanged()
    }
}